package com.qiyu.tech.shutdown.starter.conf;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author linhao
 * @date created in 6:29 下午 2020/11/6
 */
@Component
public class WebInterceptor implements HandlerInterceptor {

    static final AtomicLong nextId = new AtomicLong(0);

    static final ThreadLocal<Long> tl = ThreadLocal.withInitial(() -> nextId.getAndIncrement());

    static final ThreadLocal<DateFormat> df = ThreadLocal.withInitial(()-> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));


    /**
     * 相同的请求每次调用返回结果都是相同的
     *
     * @return
     */
    static long get() {
        return tl.get();
    }

    static DateFormat getTime(){
        return df.get();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("线程调用 pre ：" + getTime());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Thread.sleep(800);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("线程调用 after ：" + getTime());
    }
}
